<?php

namespace App\Services;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;

use Illuminate\Support\Facades\Cache;
use Exception;

class Qiniu
{
    protected $accessKey = '';
    protected $secretKey = '';
    protected $bucket = '';
    protected $auth = '';

    public $url = '';

    public function __construct()
    {
        //$config = config('filesystem.disks.qiniu');
        $setting = Config::getUploadSetting();
        $config = $setting['qiniu'] ?? [];

        // 用于签名的公钥和私钥
        $this->accessKey = $config['accesskey'];
        $this->secretKey = $config['secretkey'];
        $this->bucket = $config['bucket'];
        $this->url = $config['url'];
        // 初始化签权对象
        $this->auth = new Auth($this->accessKey, $this->secretKey);
    }

    /**
     * 获取 token
     *
     * @return string
     */
    public function getToken()
    {
        $tokenCache = Cache::get('qiniu_token_cache');
        if (!$tokenCache) {
            $key = null;
            $expires = 86400;
            // 生成上传Token
            $token = $this->auth->uploadToken($this->bucket, $key, $expires);

            Cache::put('qiniu_token_cache', $token, $expires);

            return $token;
        }

        return $tokenCache;
    }

    /**
     * 上传文件
     */
    public function uploadFile($file)
    {
        try {
            $token = $this->getToken();
            // 构建 UploadManager 对象
            $uploadManager = new UploadManager();

            $extStr = explode('.', $file['name']);
            // 重命名
            $name = uniqid() . '.' . $extStr[count($extStr) - 1];
            $filePath = $file['tmp_name'];
            $type = $file['type'];

            list($ret, $err) = $uploadManager->putFile($token, $name, $filePath, null, $type, false);
            if ($err) {
                // 上传失败
                $msg = $err->error ?? '配置信息不正确';
                return ['code' => '0', 'msg' => $msg, 'key' => ''];
            } else {
                // 成功
                return ['code' => '1', 'msg' => '上传成功', 'key' => $ret['key']];
            }
        } catch (Exception $e) {
            return ['code' => '0', 'msg' => $e->getMessage(), 'key' => ''];
        }
    }

    /**
     * 删除文件
     */
    public function delFile($key)
    {
        // 初始化 BucketManager
        $auth = $this->auth;
        $bucketMgr = new BucketManager($auth);
        $result = $bucketMgr->delete($this->bucket, $key);

        return $result;
    }
}
